// pages/module/setting/setting.js
import regeneratorRuntime from '../../../utils/runtime.js';
import { getData, setData, clearData, dataKey } from '../../../utils/storage.js';
import shareFun from '../../../utils/shareFun.js';
import {kuaidi_search,kuaidi_search_byorderno} from '../../../utils/util.js'
import {
  getPhone,
  recordGrowth,
  wxPay,
  bank_query,
  refreshInfo,
  cherckMineInfo,
  ifTaoBao_authorized,
  taoBaoAuthorizeStatus
} from '../../../utils/imapi.js';
var app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    mobile:'未绑定',
    opacity:0,
    is_audit:true,
    version:'',
    hiddenmodalput:true, //微信号
    focus:'', //微信号输入框
    wechat_alian_no:'', //微信号
	Bankcard:'', //银行卡
  channelId:wx.getStorageSync('channelId') || '',//渠道id
  uid:'', // 用户id
  isTaoBaoAuthorized:wx.getStorageSync('isTaoBaoAuthorized') || false // 淘宝渠道是否授权
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
	  
	if(this.channelId==='') {
		this.taoBaoAuthorizestatus(app.globalData.uid)
	}
    // this.ifTaoBaoAuthorized() // 判断是否淘宝授权
	  console.log(app);
    console.log(app.globalData.uid)
    shareFun.hidenShareMenu()
    //console.log(app.globalData.version);
	this.setData({
		version:app.globalData.version,
	})
  this.setData({
    uid:app.globalData.uid
  })
	var data=await cherckMineInfo();
	console.log(data.data);
	this.setData({
		wechat_alian_no:data.data.wechat_alian_no
	})
	var res=await bank_query({page_index:1,page_size:10});
	console.log(res.data);
	if(res.data.length==0){
		this.setData({
			Bankcard:'未绑定'
		})
	}else{
		this.setData({
			Bankcard:'已绑定'
		})
	}
  },
  async taoBaoAuthorizestatus(id) {
	 try {
		 const data = await taoBaoAuthorizeStatus({uid:id})
		 console.log(data);
		 this.setData({
			 channelId:data.data,
		 })
		 console.log(this.data.channelId);
		 wx.setStorageSync('channelId', data.data)
		 this.setData({
			 isTaoBaoAuthorized:true
			 
		 })
		 wx.setStorageSync('isTaoBaoAuthorized', true)
	 }catch(err) {
		 console.log(err)
	 }
  },
 //  async ifTaoBaoAuthorized() {
 //    const data =await ifTaoBao_authorized({code:'L5K61eorDD1F3gRAZhIWxgY53072875',state:uid})
 //    console.log(data);
	// console.log('1')
 //  },
  async handleGetPhoneNumber(e) {
    var result = e.detail
    var that = this;
    console.log(e)

    this.setData({
      is_audit:app.is_audit==1?true:false
    })

    if(!app.is_auth()){

      wx.showToast({
        title: '请先到我的登陆，才能绑定',
      })
      return 

    }

    if(!result.encryptedData||!result.iv){
      return
    }
    wx.checkSession({
      async success () {
        //session_key 未过期，并且在本生命周期一直有效
        var session_key ="";
        try {
           session_key = await getData(dataKey.session_key)
          console.log(session_key)
        } catch (error) {
          
        }
        const {data} = await getPhone(result.encryptedData, result.iv, session_key,true)
        // if(this.data.mobile == '未绑定'){
          recordGrowth({tasktype:3})
        // }
        await setData(dataKey.userInfo,data)
        that.setData({
          mobile:data.phone,
          
        })

        app.globalData.userInfo.phone=data.phone
      },
      async fail () {
        // session_key 已经失效，需要重新执行登录流程
        wx.login({
          success: async ({ code }) => {
            const {data} = await getPhone(result.encryptedData, result.iv, code)
            await setData(dataKey.userInfo,data)
            that.setData({
              mobile:data.phone
            })
          }
        })
      }
    })
  },
  bth(){
	  //console.log(new Date())
	  var self=this
	  // 获取小程序更新机制兼容
	  if (wx.canIUse('getUpdateManager')) {
	    const updateManager = wx.getUpdateManager()
	    //1. 检查小程序是否有新版本发布
	    updateManager.onCheckForUpdate(function (res) {
	      // 请求完新版本信息的回调
		  //console.log(res);
	      if (res.hasUpdate) {
	        //2. 小程序有新版本，则静默下载新版本，做好更新准备
	        updateManager.onUpdateReady(function () {
	          console.log(new Date())
	          wx.showModal({
	            title: '更新提示',
	            content: '新版本已经准备好，是否重启应用？',
	            success: function (res) {
	              if (res.confirm) {
	                //3. 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
	                updateManager.applyUpdate()
	              } else if (res.cancel) {
                  
                  
                  
	              }
	            }
	          })
	        })
	        updateManager.onUpdateFailed(function () {
	          // 新的版本下载失败
	          wx.showModal({
	            title: '已经有新版本了哟~',
	            content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
	          })
	        })
	      }else{
			  wx.showModal({
			    title: '提示',
			    content: '当前已为最新版本',
			  })
		  }
	    })
	  } else {
	    // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
	    wx.showModal({
	      title: '提示',
	      content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
	    })
	  }
  },

  toSuss(e){
    wx.navigateTo({
      url: '/pages/module/growth/growthUpStep2/growthUpStep2',
    })
  },
	activity(){
		wx.navigateTo({
		  url: '/packageTab/pages/activity/activity_search/activity_search?view_code=YB_ACTIVIITY',
		})
	},
	Bankcard(){
		wx.navigateTo({
		  url: '/packageTab/pages/Bankcard/Bankcard',
		})
	},
  goTaoBaoAuthorize() {
    wx.navigateTo({
      url:'/packageTab/pages/TaoBao_Authorize/TaoBao_Authorize?uid='+app.globalData.uid+'&channelId='+this.data.channelId
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  //微信号
   modalinput(){
	   if(this.data.wechat_alian_no){
		   wx.showModal({
		   			title: '提示',
		   			content: '微信号已经修改过',
		   		})
	   }else{
		   this.setData({
		   	   hiddenmodalput: !this.data.hiddenmodalput
		   	})
	  }
	   
	},
	//取消按钮
		cancel: function(){
	        this.setData({
	            hiddenmodalput: true
	        });
	    },
	    //确认
	    confirm:async function(){
			var info=await refreshInfo({wechat_alian_no:this.data.focus});
			console.log(info);
			
			this.setData({
			    hiddenmodalput: true,
				wechat_alian_no:this.data.focus
			})
			app.globalData.userInfo.wechat_alian_no = this.data.focus
			console.log(app);
	    },
		dalput(e){
			this.setData({
				focus:e.detail.value
			})
		},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      mobile:app.globalData.userInfo.phone?app.globalData.userInfo.phone:'未绑定',
      opacity:app.is_audit==true?0:0,
      is_audit:app.is_audit==1?true:false
    }),
	this.taoBaoAuthorizestatus(app.globalData.uid)
  },

  openPDDPath:function(){

    wx.navigateToMiniProgram({
	    appId: 'wx32540bd863b27570',
	    path: 'pages/personal/personal',
      success(){
      
      },
      fail(res) {
        
      }
    })
  },

  kuaidi:function(){
    kuaidi_search('78149420456084')
    
  },

  kuaidi_byorder:function(){

    kuaidi_search_byorderno('PDD','200912-257243220540291','88389851472','')


  },
  

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
	
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})